<template>
  <continer
    :showPage="showPage"
    :shadow="true"
    :pageshadow="true"
    :isNoTabs="true"
  >
    <template slot="search">
      <QuickSearch
        :advForm="quickSearchForm"
        @QuickSearch="handleSearchFun"
      ></QuickSearch>
    </template>
    <template slot="oprate">
      <el-button type="primary" size="mini" @click="handleSearchFun"
        >查询</el-button
      >
      <el-button
        size="mini"
        @click="openDrawerFun(1)"
        v-functions="['spare_mgt_stock_inbound_func']"
        >入库</el-button
      >
      <el-button
        size="mini"
        @click="openDrawerFun(2)"
        v-functions="['spare_mgt_stock_outbound_func']"
        >出库</el-button
      >
    </template>
    <template slot="content">
      <instiutionTable
        ref="tableRef"
        @currentChange="currentChangeFun"
        @sizeChange="sizeChange"
        :pages="spareTablePages"
        :instiutionTableData="spareTableData"
        :instiutionTableHeader="spareTableHeader"
      >
        <template #spareNumber="{ scope }">
          <span v-if="allCommodityCodeObj[scope.row.spareId]">{{ allCommodityCodeObj[scope.row.spareId].spareNumber }}</span>
        </template>
        <template #spareName="{ scope }">
          {{ allCommodityCodeObj[scope.row.spareId] ? allCommodityCodeObj[scope.row.spareId].name : ''
          }}<span
            v-if="allCommodityCodeObj[scope.row.spareId] && allCommodityCodeObj[scope.row.spareId].isDelete"
            class="is-plain"
            >（已删除）</span
          >
        </template>
        <template #spareTypeName="{ scope }">
          {{ scope.row.spareTypeId | filterTypeName }}
        </template>
        <template #houseName="{ scope }">
          {{ allHouseObj[scope.row.wareHouseId] ? allHouseObj[scope.row.wareHouseId].name : '' }}
        </template>
      </instiutionTable>
      <!-- 出入库抽屉 -->
      <drawer
        class="outIntoHouse"
        irection="rtl"
        size="600px"
        :title="type === 1 ? drawerData.intoTitle : drawerData.outTitle"
        :drawer="drawerData.isShow"
        @save="saveConfirm"
        @cancelFun="cancelFun('addOrEdit')"
        @closeDraw="cancelFun('addOrEdit')"
      >
        <template slot="column">
          <outIntoHouse ref="outIntoHouse" :type="type" />
        </template>
      </drawer>
    </template>
  </continer>
</template>

<script lang="ts">
import { Component, Vue, Ref, Mixins } from 'vue-property-decorator'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import instiutionTable from '@/common/views/institutionTable/institutionTable.vue'
import outIntoHouse from '@/afterSales/views/spare/stock/outIntoHouse.vue'
import drawer from '@/common/views/drawer/index.vue'
import { Form as ElForm } from 'element-ui'
import { commonAction } from '@/utils/common'
import { state, mutations } from '../store/spareData'
import filterTypeName from '../mixins/filterTypeName'
@Component({
  name: 'SparePartsStock',
  components: {
    QuickSearch,
    continer,
    instiutionTable,
    outIntoHouse,
    drawer
  }
})
export default class Category extends Mixins(filterTypeName) {
  @Ref() private readonly outIntoHouse!: outIntoHouse
  private $confirm: any
  private $message: any

  private type: number = 0 // 出入库抽屉区分 1：入库 2： 出库

  private showPage: boolean = false

  private spareTableData = [] // 表格数据

  private spareTableHeader: any[] = [ // 表头
    { label: '备件编号', prop: 'spareNumber', custom: true },
    { label: '备件名称', prop: 'spareName', custom: true },
    { label: '类型', prop: 'spareTypeName', custom: true },
    { label: '型号', prop: 'spareModel' },
    { label: '仓库', prop: 'houseName', custom: true },
    { label: '库存数量', prop: 'stockNum' }
  ]

  private spareTablePages = { // 表格分页
    current: 1,
    pageSize: 10,
    total: 100
  }

  private quickSearchForm: any = {
    form: {
      spareNumber: '',
      spareName: '',
      spareModel: '',
      warehouseId: '',
      spareTypeIds: [],
      countStart: undefined,
      countEnd: undefined
    },
    advSearchOptions: [
      { label: '备件编号', inputType: 'input', placeholder: '请输入', name: 'spareNumber', clearable: true },
      { label: '仓库', inputType: 'select', defaultProp: { label: 'name', value: 'id' }, multiple: false, clearable: true, selectData: state.houseList, name: 'warehouseId' },
      { label: '备件名称', inputType: 'input', placeholder: '请输入', name: 'spareName', clearable: true },
      { label: '类型', inputType: 'cascader', placeholder: '请输入', name: 'spareTypeIds', clearable: true, props: { value: 'id', label: 'typeName', children: 'children', expandTrigger: 'hover', checkStrictly: false, emitPath: false }, options: state.spareTypeList },
      { label: '型号', inputType: 'input', placeholder: '请输入', name: 'spareModel', clearable: true },
      { label: '数量', inputType: 'numberRange', placeholder: '请输入', preName: 'countStart', afterName: 'countEnd', clearable: true }
    ]
  } // 快捷检索数据

  private drawerData = {
    isShow: false, // 抽屉是否显示
    outTitle: '备件出库', // 出库抽屉标题
    intoTitle: '备件入库单填写' // 入库抽屉标题
  }

  private handleSearchFun () { // 搜素
    this.spareTablePages.current = 1
    this.getTableList()
  }

  private get allCommodityCodeObj () {
    console.log(state.allCommodityCodeObj)
    return state.allCommodityCodeObj
  }

  private getTableList () { // 获取表格数据
    const { spareName, spareModel, countStart, countEnd, spareTypeIds, warehouseId, spareNumber } = this.quickSearchForm.form
    const spareTypeIdsFormat = spareTypeIds && spareTypeIds.length ? [spareTypeIds.join()] : []
    const sedData = {
      limit: this.spareTablePages.pageSize,
      page: this.spareTablePages.current,
      warehouseId,
      spareTypeIds: spareTypeIdsFormat,
      spareNumber,
      spareName,
      spareModel,
      countStart,
      countEnd
    }
    commonAction({
      url: '/server-work/action/stock/list',
      method: 'post',
      data: sedData
    }).then(res => {
      if (res.success) {
        const { list, count } = res.data
        this.spareTableData = list
        this.spareTablePages.total = count
      }
    })
  }

  private currentChangeFun (page: number) { // 翻页
    this.spareTablePages.current = page
    this.getTableList()
  }

  private sizeChange (size: number) { // 页码数量变化
    this.spareTablePages.pageSize = size
    this.getTableList()
  }

  private openDrawerFun (type: number) { // 出入库
    this.drawerData.isShow = true
    this.type = type
    if (this.outIntoHouse) { // 清空出入库数据
      this.outIntoHouse.clearPopData()
      this.outIntoHouse.accessForm = {
        wareHouseId: '',
        stockTypeId: '',
        // ticketId: '', // 关联工单ID暂时不做
        description: ''
      }
    }
  }

  private saveConfirm () { // 保存出入库数据
    const formRef = this.outIntoHouse.$refs.accessForm as ElForm
    const spareList: any = [] // 添加的备件数据
    this.outIntoHouse.dataList.forEach(item => {
      spareList.push({
        count: item.number,
        spareId: item.id,
        spareModel: item.model,
        spareTypeId: item.typeId
      })
    })
    const { description, wareHouseId, stockTypeId } = this.outIntoHouse.accessForm // 表单数据
    formRef.validate(valide => {
      if (valide) {
        if (spareList && !spareList.length) { // 入库是否添加备件
          return this.$message.error(`请添加${this.type === 1 ? '入' : '出'}库的备件`)
        }
        const spareNum = spareList.some(item => item.count <= 0 || item.count === null || item.count === undefined) // 判读入库备件的数量是否都 > 0
        if (spareNum) {
          return this.$message.error(`${this.type === 1 ? '入' : '出'}库数量需大于0`)
        }
        const spareCount = spareList.reduce((prev, cur) => { // 出入库数量和
          prev = prev + cur.count
          return prev
        }, 0)
        const sendData = {
          spareList,
          // ticketId,
          description,
          wareHouseId,
          stockTypeId,
          spareCount,
          type: this.type === 1 ? 'rk' : 'ck'
        }
        commonAction({ url: '/server-work/action/stock/spareStock', method: 'post', data: sendData }).then(res => {
          if (res.success) {
            this.drawerData.isShow = false
            this.getTableList()
            this.$message.success(`${this.type === 1 ? '入' : '出'}库已完成,该库存的对应备件数量已经完成变更`)
          }
        })
      }
    })
  }

  private cancelFun () { // 关闭抽屉
    this.drawerData.isShow = false
  }

  private get allSpareTypeObj () {
    return state.allSpareTypeObj
  }

  private get allHouseObj () {
    return state.allHouseObj
  }

  private formateOptions (val) {
    if (val) {
      val.forEach(item => {
        if (item.children) {
          item.children = this.formateOptions(item.children)
        }
      })
      const arr = val.filter(item => item.isDelete === 0)
      if (arr.length) {
        return arr
      } else {
        return null
      }
    }
  }

  private get isStoreEmpty () {
    return state.spareTypeList.length === 0 || state.spareOutStockTypeList.length === 0 || state.spareInStockTypeList.length === 0 || state.unitList.length === 0
  }

  private activated () {
    if (this.isStoreEmpty) { // 防止首次数据为空、拉取最新配置数据
      commonAction({
        url: '/server-work/action/spareConfig/list',
        method: 'get'
      }).then(res => {
        if (res.success) {
          mutations.setStateData('arr', 'spareTypeList', this.formateOptions(res.data.spareTypeList) || [])
          mutations.setStateData('arr', 'spareOutStockTypeList', res.data.spareOutStockTypeList)
          mutations.setStateData('arr', 'spareInStockTypeList', res.data.spareInStockTypeList)
          mutations.setStateData('arr', 'unitList', res.data.unitConfig)
          this.quickSearchForm.advSearchOptions[3].options = state.spareTypeList
        }
      })
    } else {
      this.quickSearchForm.advSearchOptions[3].options = state.spareTypeList
    }
    if (!state.houseRequestDone) {
      commonAction({
        url: '/server-work/action/wareHouse/query',
        method: 'post',
        data: { isIncludeDel: false }
      }).then(res => {
        if (res.success) {
          mutations.setRequestData('house', true)
          mutations.setStateData('arr', 'houseList', res.data.wareHouseItemList)
          this.quickSearchForm.advSearchOptions[1].selectData = state.houseList
        }
      })
    } else {
      this.quickSearchForm.advSearchOptions[1].selectData = state.houseList
    }
    if (!state.getAllCommondity) {
      commonAction({
        url: '/server-work/action/spare/query',
        method: 'post',
        data: { isIncludeDel: true }
      }).then(res => {
        if (res.success) {
          mutations.setStateData('obj', 'allCommodityCodeObj', res.data.spareItemList)
          mutations.setRequestData('spare', true)
        }
      })
    }
  }

  private mounted () {
    this.getTableList()
  }
}
</script>

<style lang="stylus" scoped>
>>> .el-input-number
  .el-input__inner
    text-align left
.outIntoHouse
  >>> .drawer-contain
    height calc(100vh - 120px)
  >>> .el-table::before
    width 0
</style>
